import { deepClone } from "Yan/utils/util"
import FormValidators from 'Yan/utils/validators'
import request from '@/utils/request'

export default {
  // inject: ['refList', 'formConfig', 'getGlobalDsv', 'globalOptionData', 'globalModel', 'getOptionData'],
  inject: ['globalModel'],
  data() {
    return {
      field: {},
      // options: {}
    }
  },
  computed: {
    fieldLib() {
      return this.designer.fieldLib;
    },
    layoutType() {
      return this.designer.getLayoutType();
    },
    previewStatus() {
      return this.designer.previewStatus
    }
  },
  created() {
    this.field = this.designer.fieldLib[this.fieldId]
  },
  mounted() {
    if (this.designer.designStatus) {
      this.designer.handleEvent(`fieldOptionChange_${this.fieldId}`, (newValue) => {
        // console.log(`fieldOptionChange_${this.fieldId}`, newValue)
        // this.field = newValue
        this.$set(this.field, 'options', newValue.options)
        this.fieldModel = newValue.options.defaultValue
        if (newValue.type === 'table') this.fieldModel = [{}]
        else if (newValue.type === 'checkbox') {
          if (!newValue.options.defaultValue) this.fieldModel = []
        }
        this.handleOptionItemsAsync();
        this.buildFieldRules()
        this.initEventHandler()
      });
    }
  },
  methods: {
    // --------------------- 组件内部方法 begin ------------------ //
    // 初始化表单单元的初始值
    initFieldModel() {
      if (this.field.options.defaultRowValue && typeof this.field.options.defaultRowValue === 'string') {
        this.formData[this.fieldId] = JSON.parse(this.field.options.defaultRowValue)
      }
      // if (this.field.type === 'table') this.fieldModel = this.formModel[this.fieldId] || [{}]
      // else this.fieldModel = this.formModel[this.fieldId]
    },
    // 添加对应字段的监听事件
    initEventHandler() {
      if (this.previewStatus) return
      if (!this.field.options.readonly || !this.field.options.disabled) return
      if (this.field.options.onListener) {
        // let listenerFu = new Function(this.field.options.onListener)

        const { onListener } = this.field.options
        let FunString = onListener
        FunString = FunString.replace(/(\$[^$]+\$)/g, (iStr) => {
          return `this.formModel.${iStr.slice(1, -1).split('%')[0]}`
          // return iStr.slice(1, -1).split('%')[0]
        })
        const listenerFu = new Function(FunString)
        const listenerArray = this.field.options.onListener.match(/((\$[^$]+\$))/g)
        // console.log('lst arr', listenerArray, FunString)
        if (listenerArray) {
          listenerArray.forEach((i) => {
            const listenKey = i.slice(1, -1).split('%')[0]
            this.globalModel.$watch(`formModel.${listenKey}`, () => {
              const lstVal = listenerFu.call(this)
              if (lstVal !== void 0) {
                this.formData[this.fieldId] = lstVal
              }
            })
            // this.globalModel.$on(`${listenKey}-changed`, () => {
            //   // console.log(this.fieldId, `${listenKey}-changed`)
            //   const lstVal = listenerFu.call(this)
            //   if (lstVal !== void 0) {
            //     // console.log(this.fieldId, 'to change', lstVal)
            //     this.formData[this.fieldId] = lstVal
            //     // this.syncUpdateFormModel(lstVal)
            //     // this.initFieldModel()
            //   }
            // })
          })
        }
      }
    },
    // 构建字段验证
    buildFieldRules() {
      if (!this.field.formItemFlag && this.field.options.hidden) return
      if (!this.rules) return
      // console.log('in buildFieldRules', this.rules)
      this.rules.splice(0, this.rules.length) // 清空已有
      if (this.field.options.required) {
        this.rules.push({
          required: true,
          // trigger: ['blur', 'change'],
          trigger: ['blur'], /* 去掉change事件触发校验，change事件触发时formModel数据尚未更新，导致radio/checkbox必填校验出错！！ */
          message: this.field.options.requiredHint || '字段值不可为空',
        })
      }

      if (this.field.options.validation) {
        const vldName = this.field.options.validation
        if (FormValidators[vldName]) {
          this.rules.push({
            validator: FormValidators[vldName],
            trigger: ['blur', 'change'],
            label: this.field.options.label,
            errorMsg: this.field.options.validationHint
          })
        } else {
          this.rules.push({
            validator: FormValidators['regExp'],
            trigger: ['blur', 'change'],
            regExp: vldName,
            label: this.field.options.label,
            errorMsg: this.field.options.validationHint
          })
        }
      }

      if (this.field.options.onValidate) {
        const customFn = (rule, value, callback) => {
          const tmpFunc = new Function('rule', 'value', 'callback', this.field.options.onValidate)
          return tmpFunc.call(this, rule, value, callback)
        }
        this.rules.push({
          validator: customFn,
          trigger: ['blur', 'change'],
          label: this.field.options.label
        })
      }
      // console.log(this.rules)
    },

    /**
     * 加载选项，并清空字段值
     * @param options
     */
    loadOptions(options) {
      this.field.options.optionItems = deepClone(options)
      // this.clearSelectedOptions()  //清空已选选项
    },

    /**
     * 重新加载选项，不清空字段值
     * @param options
     */
    reloadOptions(options) {
      this.field.options.optionItems = deepClone(options)
    },
    // --------------------- 事件处理 begin ------------------ //
    // 发送字段数据更新
    emitFieldDataChange(newValue, oldValue) {
      this.$emit('field-value-changed', [newValue, oldValue])
      // Yan-这部分应该会触发其他字段添加了的监听事件
    },
    // 触发表单单元onCreated事件
    handleOnCreated() {
      if (this.field.options.onCreated) {
        const customFunc = new Function(this.field.options.onCreated)
        const createValue = customFunc.call(this)
        if (createValue) this.formData[this.fieldId] = createValue
        //  this.syncUpdateFormModel(createValue)
      }
    },
    // 触发表单单元onMounted事件
    handleOnMounted() {
      if (this.field.options.onMounted) {
        const mountFunc = new Function(this.field.options.onMounted)
        mountFunc.call(this)
      }
    },
    // 触发表单单元Focus(焦点)事件
    handleFocusCustomEvent(event) {
      this.oldFieldValue = deepClone(this.fieldModel) // 保存修改change之前的值
      if (this.field.options.onFocus) {
        const customFn = new Function('event', this.field.options.onFocus)
        customFn.call(this, event)
      }
    },
    // 触发表单单元Blur(失焦)事件
    handleBlurCustomEvent(event) {
      if (this.field.options.onBlur) {
        const customFn = new Function('event', this.field.options.onBlur)
        customFn.call(this, event)
      }
    },
    // 触发表单单元Change(改变)事件
    /* input的清除输入小按钮会同时触发handleChangeEvent、handleInputCustomEvent！！ */
    handleChangeEvent(value) {
      // console.log('handleChangeEvent', value)
      // number组件一般不会触发focus事件，故此处需要手工赋值oldFieldValue！！
      this.oldFieldValue = deepClone(value) /* oldFieldValue需要在initFieldModel()方法中赋初值!! */
    },
    // 按钮点击事件
    handleButtonWidgetClick() {
      // 设计状态不触发点击事件
      if (this.designer.designState) return

      if (this.field.options.onClick) {
        const changeFn = new Function('formData', this.field.options.onClick)
        changeFn.call(this, this.formData)
      }
    },
    // 触发表单单元Input(输入)事件
    handleInputCustomEvent(value) {
      if (this.field.options.onInput) {
        const customFn = new Function('value', this.field.options.onInput)
        customFn.call(this, value)
      }
    },
    // 从接口请求选项列表
    async handleOptionItemsAsync() {
      // console.log('handleOptionItemsAsync', this.designer.previewStatus)
      if (this.designer.previewStatus) return
      if (this.field.options.optionItemsAsync) {
        const customFn = new Function('request', this.field.options.optionItemsAsync)
        const OptionItems = await customFn.call(this, request)
        // console.log('handleOptionItemsAsync', OptionItems)
        if (OptionItems) this.customOptionItems = OptionItems
      }
    },
    // 触发后置的按钮点击事件
    emitAppendButtonClick() {
      if (this.designState) return; // 设计状态不触发点击事件
      if (this.field.options.onAppendButtonClick) {
        const customFn = new Function(this.field.options.onAppendButtonClick)
        customFn.call(this)
      }
      // Yan---不清楚这部分具体起到什么作用
      //  else {
      //   /* 必须调用mixins中的dispatch方法逐级向父组件发送消息！！ */
      //   this.dispatch('VFormRender', 'appendButtonClick', [this])
      // }
    },
    // -------------------------编辑状态 组件公共方法-------------------------------- //

  }
}
